using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.StepStandards.Commands;

/// <summary>
/// 工艺标准更新命令。
/// </summary>
public sealed record UpdateStepStandardCommand(long Id, ProcStepStandardDto StepStandard) : IRequest<IResult<bool>>;

internal sealed class UpdateStepStandardCommandHandler(IRepository<ProcStepStandard> repo) : IRequestHandler<UpdateStepStandardCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateStepStandardCommand request, CancellationToken cancellationToken)
    {
        // 检查编码不能重复
        var exists = await repo.AsQueryable()
            .WhereIF(request.StepStandard.StepTaskId > 0, m => m.StepTaskId == request.StepStandard.StepTaskId)
            .AnyAsync(m => m.StepId == request.StepStandard.StepId && m.ParameterCode == request.StepStandard.ParameterCode && m.Id != request.Id, cancellationToken);
        if (exists)
        {
            return Result.Failure("工序参数编码已存在");
        }

        var standard = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (standard == null)
        {
            return Result.Failure("未找到要更新的工艺标准");
        }

        standard.ParameterName = request.StepStandard.ParameterName;
        standard.ParameterCode = request.StepStandard.ParameterCode;
        standard.Symbol = request.StepStandard.Symbol;
        standard.SymbolIndex = request.StepStandard.SymbolIndex;
        standard.StandardValue = request.StepStandard.StandardValue;
        standard.Tolerance = request.StepStandard.Tolerance;
        standard.MinLimit = request.StepStandard.MinLimit;
        standard.MaxLimit = request.StepStandard.MaxLimit;
        standard.MeasurementUnit = request.StepStandard.MeasurementUnit;
        standard.InspectionMethod = request.StepStandard.InspectionMethod;
        standard.Conversion = request.StepStandard.Conversion;
        standard.Digits = request.StepStandard.Digits;

        var ok = await repo.UpdateAsync(standard, m => new
        {
            m.ParameterName,
            m.ParameterCode,
            m.Symbol,
            m.SymbolIndex,
            m.StandardValue,
            m.Tolerance,
            m.MinLimit,
            m.MaxLimit,
            m.MeasurementUnit,
            m.InspectionMethod,
            m.Conversion,
            m.Digits,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
